/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cnam.mobileshopping.ejb.user;

import java.util.List;
import java.util.UUID;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.cnam.mobileShopping.entity.User;

/**
 *
 * @author A.Cazenave
 */
@Stateless(mappedName="ejb/mobileshopping/user")
@Local(UserLocal.class)
@Remote(UserRemote.class)
public class UserBean implements UserLocal, UserRemote {

    @PersistenceContext(unitName="mobileshopping-corePU")
    EntityManager entityManager;
    
    public User getUserById(int userId) {
        return entityManager.find(User.class, userId);
    }

 
    
    public User getUserByLogin(String login) {
        if(login != null){
          java.util.List<User> users = entityManager.
                  createNamedQuery("User.findByLogin").
                  setParameter("login", login)
                  .getResultList();
          if(users != null && users.size() == 1){
              return users.get(0);
          }else{
              return null;
          }
        } else {
            throw new NullPointerException("login is null");
        }
    }
    
    public User getUserByLoginAndPassword(String login, String password) {
        if(login != null && password != null){
          java.util.List<User> users = entityManager.createNamedQuery("User.findByLoginAndPassword").setParameter("login", login).setParameter("password",password).getResultList();
          if(users != null && users.size() == 1){
              return users.get(0);
          }else{
              return null;
          }
        } else {
            throw new NullPointerException("id is null OR password is null");
        }
    }

    public User addUser(String pseudo, String login, String password) {
        if (login != null && pseudo != null && password != null){
            User u = new User();
            u.setLogin(login);
            u.setPwd(password);
            u.setPseudo(pseudo);
            u.setCommonid(UUID.randomUUID().toString());
            entityManager.persist(u);
            return u;
         } else {
             throw new NullPointerException("login is null OR pseudo is null OR password is null");
        }
    }

    @Override
    public User updateUser(int userId, String login) {
        if (login != null && userId > 0 ){
            User u = getUserById(userId);
            u.setLogin(login);
            entityManager.merge(u);
            return u;
         } else {
             throw new NullPointerException("login is null OR pseudo is null OR password is null");
        }
    }

    @Override
    public List<User> getUsers() {
       return entityManager.createNamedQuery("User.findAll").getResultList();
    }
    
    
}
